﻿Console = function () {
    this.readlineCallback = null;
    this.waitingForInput = false;
    this.console = null;
};

Console.prototype.SetWindow = function (console) {
    this.console = console;
};

Console.prototype.Write = function (content) {
    if (!this.lastLine().length)
        this.createNewLine();

    this.lastLine().append(content);
    
    //this.console.window.scrollTo(0, $(console.document).height());
};

Console.prototype.WriteLine = function (content) {
    this.Write(content);
    this.createNewLine();
};

Console.prototype.Clear = function () {
    this.c$(".consoleLine").detach();
};

Console.prototype.createNewLine = function () {
    $(this.console).append("<div class=\"consoleLine\"></div>");
};

Console.prototype.c$ = function (selector) {
    return $(selector, $(this.console));
};

Console.prototype.lastLine = function () {
    return this.c$("div:last");
};

Console.prototype.ReadLine = function (callback) {
    if (this.waitingForInput)
        throw "MultipleReadLineException";

    this.readlineCallback = callback;
    this.addPrompt();
    this.Focus();
};

Console.prototype.addPrompt = function () {
    this.Write("<input type=\"text\" id=\"consoleInput\" class=\"prompt\" />");
    this.c$("#consoleInput").keydown({ c: this }, function (event) { event.data.c.handleInput(event); });
};

Console.prototype.handleInput = function (event) {
    if (event.keyCode != 13)
        return;

    var input = this.c$("#consoleInput").val();
    this.c$("#consoleInput").detach();

    this.Write("<span>" + input + "</span>");

    this.createNewLine();

    var callback = this.readlineCallback;
    this.readlineCallback = null;
    this.waitingForInput = false;

    if (callback)
        callback(input);
};

Console.prototype.Focus = function () {
    this.c$("#consoleInput").focus();
};

Console.prototype.WriteHeader = function ()
{
    this.Clear();
    this.WriteLine("----------------------------------------------------------------------------------");
    this.WriteLine("jsCLR v1.0");
    this.WriteLine("----------------------------------------------------------------------------------");
    this.WriteLine("&nbsp;");  
};